<template>
  <div id="table" class>
    <el-row>
      <el-col :span="24">
        <div class="table-grid-content list-table btnDiy">
          <div>
            <div class="tag-views-title">
              {{ $t('查询视图') }}：
              <el-button size="mini" @click="managementView">{{ $t('管理视图') }}</el-button>
              <el-button size="mini" @click="addView">{{ $t('新建视图') }}</el-button>
            </div>

            <el-button size="mini" @click="upload.open = true">{{ $t('导入') }}</el-button>
            <el-button size="mini" @click="exportDeal()">{{ $t('导出') }}</el-button>
            <el-button v-hasPermi="['fund:fundbase:edit']" type="primary" size="mini" @click="addHandle()">{{ $t('添加') }}</el-button>
          </div>
          <div class="viewItem">
            <ul class="list-views">
              <li
                v-for="(item,index) in listSysSearch"
                :key="index"
                :class="[{selected: activeItem === item.viewId}]"
                :style="{'background':item.color}"
                @click="sysSearchActive(item)"
              >
                <div class="tag-number">{{ item.count }}</div>
                <div class="tag-label">{{ $t(item.viewName) }}</div>
              </li>
            </ul>
          </div>
        </div>
      </el-col>
    </el-row>

    <!-- 表格 -->
    <div class="Table-table list-table">
      <div v-if="fundBaseList !== null || fundBaseList !== [] || fundBaseList.length > 0" v-loading="loading" class="tableDiv">
        <el-table tooltip-effect="darkTable" :data="fundBaseList" border class="nowrapTable sortTable" @sort-change="dataSort">
          <el-table-column
            v-for="(item, index) in showFieldList"
            v-show="item.isShow === 'Y'"
            :key="index"
            sortable="custom"
            :width="item.width"
            :label="$t(item.fieldRemark)"
            :prop="item.fieldName"
            show-overflow-tooltip
            :fixed="item.isShow === 'Y' && item.isFixed === 'Y'"
          >
            <template slot="header">
              <span class="fieldName">
                <p :title="$t(item.fieldRemark)">{{ $t(item.fieldRemark) }}</p>
              </span>
              <fieldQuery :field-val="item" :group-hidden="false" @queryData="getQueryData" />
            </template>
            <template slot-scope="scope">
              <!-- 添加关注功能 -->
              <div v-if="item.fieldName === '公司简称'" class="focusTit">
                <Focus :source-id="scope.row['基金ID']" :focus="scope.row['是否关注']" :source-name="scope.row['公司简称']" focus-type="fund" />
                <router-link
                  v-if="item.fieldName === '公司简称'"
                  target="_blank"
                  :to="{path:'/fund/fundBaseSpvHome',query:{id:scope.row['基金ID']}}"
                  class="link_a"
                  @click.native="recorePath({ fromPath: $route.fullPath, path:'/fund/fundBaseSpvHome',query:{id:scope.row['基金ID']}})"
                >
                  <!-- <ToolTipBreak :content="scope.row['基金简称']" /> -->
                  {{ $t(scope.row['公司简称']) }}
                </router-link>
              </div>
              <div v-else class="cell">
                <!-- <ToolTipBreak :content="scope.row[item.fieldName]" /> -->
                {{ $t(scope.row[item.fieldName]) }}
              </div>
            </template>
          </el-table-column>

          <el-table-column :label="$t('操作')" align="center" class-name="small-padding fixed-width" width="160px" fixed="right">
            <template slot="header">
              <i class="el-icon-s-tools" style="display: inline-block;margin: 0 auto;" @click="fieldChange(viewId)" />
            </template>
            <template slot-scope="scope">
              <el-button
                v-hasPermi="['fund:fundbase:edit']"
                size="small"
                type="text"
                icon="el-icon-edit"
                @click="updateHandle(scope.row)"
              >{{ $t('修改') }}</el-button>
              <el-button
                v-hasPermi="['fund:fundbase:remove']"
                size="small"
                type="text"
                icon="el-icon-delete"
                @click="deleteHandle(scope.row)"
              >{{ $t('删除') }}</el-button>
            </template>
          </el-table-column>
        </el-table>
        <pagination
          v-show="total>0"
          class="dealPage"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          :parameter="true"
          @pagination="getList"
          @currentChange="currentChange"
        />
        <!-- parameter只项目、基金用到 -->

        <!-- 添加或修改基金基本信息对话框 -->
        <el-dialog :title="$t('基金基本信息')" :visible.sync="formOpen" :close-on-click-modal="false" :lock-scroll="false" custom-class="dialogForm" append-to-body>
          <onlineForm v-if="fundBaseFormFlag && fundBaseFormFlag==='configForm'" ref="onlineForm" cut-off-type="fund" />
          <fundBaseSpvForm v-else ref="fundBaseSpvForm" />
        </el-dialog>
      </div>
    </div>

    <!-- 导入窗口 -->
    <el-dialog :title="$t('导入')" :visible.sync="upload.open" width="400px" :close-on-click-modal="false" :lock-scroll="false">
      <div v-loading="upload.loading">
        <el-upload
          ref="upload"
          :limit="1"
          accept=".xlsx, .xls"
          :headers="upload.headers"
          :action="upload.url"
          :disabled="upload.isUploading"
          :on-progress="handleFileUploadProgress"
          :on-success="handleFileSuccess"
          :on-exceed="handleFileExceed"
          :on-change="handleFileChange"
          :auto-upload="false"
          drag
        >
          <i class="el-icon-upload" />
          <div class="el-upload__text">
            {{ $t('将文件拖到此处，或') }}
            <em>{{ $t('点击上传') }}</em>
          </div>
          <div slot="tip" class="el-upload__tip" style="color:red">
            {{ $t('提示：仅允许导入“xls”或“xlsx”格式文件！') }}
            <el-link type="primary" style="font-size:12px" @click="fetchTemplate">
              {{ $t('下载模板') }}
            </el-link>
          </div>
        </el-upload>
        <div slot="footer" class="dialog-footer" style="text-align: right;">
          <el-button @click="upload.open = false">{{ $t("取消") }}</el-button>
          <el-button type="primary" @click="submitFileForm">{{ $t("确定") }}</el-button>
        </div>
      </div>
    </el-dialog>
    <!-- 新建视图 -->
    <el-dialog v-el-drag-dialog :title="$t('新建视图')" :visible.sync="newView" width="70%" :close-on-click-modal="false" :lock-scroll="false" custom-class="dialogForm">
      <sysSearchMainForm ref="sysSearchMainForm" :module="searchKey" />
    </el-dialog>
    <!-- 管理视图 -->
    <el-dialog v-el-drag-dialog :title="$t('管理视图')" :visible.sync="oddView" width="50%" :close-on-click-modal="false" :lock-scroll="false" :before-close="handleDialogClose">
      <sysSearchMainList ref="sysSearchMainList" :module="searchKey" :view-id="viewId" />
    </el-dialog>

    <!-- fieldShow -->
    <el-dialog v-el-drag-dialog :title="$t('展示字段(字段可拖拽排序)')" :visible.sync="fieldShow" width="50%" :close-on-click-modal="false" :lock-scroll="false" :before-close="handleDialogClose" custom-class="dialogForm">
      <fieldShow ref="fieldShow" />
    </el-dialog>
  </div>
</template>
<script>
import sysSearchMainForm from '../../system/search/sysSearchMainForm'
import sysSearchMainList from '../../system/search/sysSearchMainList'
import fieldQuery from '../../system/search/fieldQuery'
import fieldShow from '../../system/search/fieldShow'
import { delFundBase, exportFundBase } from '@/api/fund/fundBase'
import Focus from '@/components/Focus/star'
import { getByUser, getDataListByView } from '@/api/system/search/searchMainView'
import fundBaseSpvForm from './fundBaseSpvForm'
import { getToken } from '@/utils/auth'
import { queryFundPortfolio } from '@/api/deal/projectInvestmentSituation/projectInvestmentSituation'
import { getConfigKey } from '@/api/system/config'
import onlineForm from '@/views/system/desform/release/onlineForm.vue'

export default {
  components: {
    Focus,
    fieldQuery,
    sysSearchMainList,
    sysSearchMainForm,
    fundBaseSpvForm,
    fieldShow,
    onlineForm
  },
  data() {
    return {
      // 菜单标识-用来查询项目内菜单
      menuKey: '',
      // 高级查询的key
      searchKey: '',
      // 基金状态
      fundStatus: '',
      selected: false,
      // 遮罩层
      loading: true,
      // 总条数
      total: 0,
      // 基金基本信息表格数据
      fundBaseList: [],
      showFieldList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      formOpen: false,
      fieldShow: false,
      oddView: false,
      newView: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        searchOrderByVo: {
          prop: '',
          order: ''
        }
      },
      // 查询列表
      listSysSearch: [],
      viewId: '',
      activeItemFund: [],
      activeItem: '',
      searchQueryList: [],
      // 基金导入参数
      upload: {
        // 是否显示弹出层（项目导入）
        open: false,
        // 弹出层标题（项目导入）
        title: '',
        // 是否禁用上传
        isUploading: false,
        // 设置上传的请求头部
        headers: { Authorization: 'Bearer ' + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + '/spv/fundBaseSpv/importData',
        // 遮罩层
        loading: false
      },
      // 基金spv配置表单切换
      fundBaseFormFlag: null,
      // 表单spv配置-基金spv表单id
      fundBaseFormTempletId: null
    }
  },
  watch: {
    '$route': {
      handler(val) {
        this.searchKey = val.query.searchKey
        this.menuKey = val.query.menuKey
        this.fundStatus = val.query.fundStatus

        this.load(this.searchKey)
      },
      deep: true,
      immediate: true
    }
  },
  created() {
    getConfigKey('fund_base_spv_form').then(res => {
      this.fundBaseFormFlag = res.msg
    })
    getConfigKey('fundSpvTempletId').then((res) => {
      this.fundBaseFormTempletId = res.msg
    })
  },
  mounted() {
  },
  methods: {
    load(val) {
      this.loading = true
      // 定位勾选视图
      getByUser(val).then(response => {
        this.listSysSearch = response.data
        if (localStorage.getItem('activeIdFund') === 'undefined') {
          this.sysSearchActive(response.data[0])
        } else {
          const index = response.data.findIndex(children => children.viewId === localStorage.getItem('activeIdFund'))
          if (index !== -1) {
            this.sysSearchActive(response.data[index])
          } else {
            this.sysSearchActive(response.data[0])
          }
        }
      })
    },
    // 查询
    getQueryData(data) {
      if (!(this.searchQueryList instanceof Array)) {
        this.$set(this, 'searchQueryList', [])
      }
      this.$nextTick(() => {
        var searchQueryTempList = []
        this.searchQueryList.forEach(item => {
          if (item.fieldName !== data.fieldName) {
            searchQueryTempList.push(item)
          }
        })
        this.searchQueryList = searchQueryTempList
        if (data.value !== '' || data.conditions !== '') {
          this.searchQueryList.push(data)
        }
        this.queryParams.searchQueryVoList = this.searchQueryList
        // this.getList(this.searchQueryList)
        this.loading = true
        this.fundBaseList = []
        getDataListByView(this.queryParams).then(res => {
          this.fundBaseList = res.data.rows
          this.total = res.data.total
          this.loading = false
        })
      })
    },
    // 删除，排序，新增只刷新视图
    getViewList(id) {
      // 查询高级查询列表
      const rows = []
      getByUser(this.$route.query.searchKey).then(response => {
        this.listSysSearch = response.data
        this.listSysSearch.forEach(item => {
          rows.push(item.viewId)
        })
      })
      // 删除当前选中视图，重新定位视图
      if (!rows.includes(localStorage.getItem('activeIdFund'))) {
        this.sysSearchActive(this.listSysSearch[0])
      }
      // 修改当前视图应刷新列表
      if (id === localStorage.getItem('activeIdFund')) {
        this.getList()
      }
    },
    // 管理视图
    managementView() {
      this.oddView = true
      console.log(this)
      if (this.$refs.sysSearchMainList) {
        this.$refs.sysSearchMainList.getList()
      }
    },
    addView() {
      this.newView = true
      if (this.$refs.sysSearchMainForm) {
        this.$refs.sysSearchMainForm.init()
      }
    },
    // 弹窗关闭按钮
    handleDialogClose() {
      this.oddView = false
      this.fieldShow = false
    },
    // 查询项目
    sysSearchActive(data) {
      if (data?.viewId !== undefined) {
        this.activeItem = this.viewId = data.viewId
        localStorage.setItem('activeIdFund', data.viewId)
        this.$nextTick(function() {
          // 项目列表
          this.queryParams.viewId = data.viewId
          this.queryParams.searchQueryVoList = []
          this.getList()
        })
      }
    },
    // 查询数据
    getList() {
      this.loading = true
      this.showFieldList = this.fundBaseList = []
      getDataListByView(this.queryParams).then(res => {
        this.showFieldList = res.datas.showFieldList
        this.fundBaseList = res.data.rows
        this.total = res.data.total
        this.loading = false
      })
    },
    // 展示字段
    fieldChange(id) {
      this.fieldShow = true
      this.$nextTick(() => {
        if (this.$refs.fieldShow) {
          this.$refs.fieldShow.getListById(id)
        }
      })
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        fundName: undefined,
        fundNamePinyin: undefined,
        fundStatus: '0',
        fundType: undefined,
        creditCode: undefined,
        registeredProvince: undefined,
        registeredCity: undefined,
        registeredAddress: undefined,
        foundationDate: undefined,
        duration: undefined,
        investmentPeriod: undefined,
        dueDate: undefined,
        settlingDate: undefined,
        investOriginDate: undefined,
        investDueDate: undefined,
        extensionPeriod: undefined,
        extensionOriginDate: undefined,
        extensionDueDate: undefined,
        targetAmount: undefined,
        currency: undefined,
        investmentMode: undefined,
        createBy: undefined,
        createTime: undefined,
        updateBy: undefined,
        updateTime: undefined,
        remark: undefined,
        delFlag: undefined
      }
      this.resetForm('form')
    },

    /** 新增按钮操作 */
    addHandle() {
      this.formOpen = true
      this.title = '添加基金基本信息'
      this.$nextTick(() => {
        if (this.fundBaseFormFlag && this.fundBaseFormFlag === 'configForm') {
          this.$refs.onlineForm.initId(this.fundBaseFormTempletId)
          this.$refs.onlineForm.init(null)
        } else {
          this.$refs.fundBaseSpvForm.init()
        }
      })
    },
    /** 修改按钮操作 */
    updateHandle(row) {
      this.formOpen = true
      this.title = '修改基金基本信息'
      this.$nextTick(() => {
        // 调用form页面的 init 方法初始化数据
        var data = {}
        data.id = row['基金ID']
        if (this.fundBaseFormFlag && this.fundBaseFormFlag === 'configForm') {
          this.$nextTick(() => {
            this.$refs.onlineForm.initId(this.fundBaseFormTempletId)
            this.$refs.onlineForm.init(data)
          })
        } else {
          this.$refs.fundBaseSpvForm.init(data)
        }
      })
    },
    /** 删除按钮操作 */
    deleteHandle(row) {
      this.$confirm(this.$t('是否确认删除?'), this.$t('警告'), {
        confirmButtonText: this.$t('确定'),
        cancelButtonText: this.$t('取消'),
        type: 'warning'
      }).then(() => {
        queryFundPortfolio({ 'fundId': row['基金ID'] }).then(response => {
          if (response.total > 0) {
            this.$alert(this.$t('SPV投资组合中存在项目，无法删除!'), this.$t('提示'), {
              confirmButtonText: this.$t('关闭'),
              type: 'error'
            })
          } else {
            this.deleteFundInfo(row)
          }
        })
      })
    },
    // 删除基金
    deleteFundInfo(row) {
      delFundBase(row['基金ID']).then(response => {
        if (response.code === 200) {
          this.getList()
          this.getViewList()
          this.msgSuccess(this.$t('删除成功'))
        }
      })
    },
    /** 导出按钮操作 */
    exportHandle() {
      const queryParams = this.queryParams
      this.$confirm(this.$t('是否确认导出?'), this.$t('警告'), {
        confirmButtonText: this.$t('确定'),
        cancelButtonText: this.$t('取消'),
        type: 'warning'
      }).then(function() {
        return exportFundBase(queryParams)
      }).then(response => {
        this.download(response.msg)
      }).catch(function() {
      })
    },
    // 分页保持排序
    currentChange(page) {
      console.log(page)
      this.loading = true
      getDataListByView(this.queryParams).then(res => {
        this.fundBaseList = res.data.rows
        this.loading = false
      })
    },
    // 排序
    dataSort(column) {
      this.loading = true
      this.queryParams.pageNum = 1
      this.queryParams.viewId = this.viewId
      var searchOrderByVo = {}
      searchOrderByVo.prop = column.prop
      searchOrderByVo.order = column.order
      this.queryParams.searchOrderByVo = searchOrderByVo
      getDataListByView(this.queryParams).then(res => {
        this.fundBaseList = res.data.rows
        this.loading = false
      })
    },
    // 文件上传中处理
    handleFileUploadProgress() {
      this.upload.isUploading = true
      // this.upload.loading = true
    },
    // 文件上传成功处理
    handleFileSuccess(response) {
      console.log(response)
      this.upload.open = false
      this.upload.isUploading = false
      // this.upload.loading = false
      this.$refs.upload.clearFiles()
      if (response.msg === 'success') {
        this.msgSuccess(this.$t('导入成功'))
      } else if (response.code === 500) {
        this.msgError(this.$t('数据异常'))
      } else {
        this.$alert(response.msg, this.$t('导入结果'), { dangerouslyUseHTMLString: true })
      }
      this.getList()
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit()
    },
    // 文件达到上限处理
    handleFileExceed() {
      this.msgError(this.$t('可上传文件数量已达到上限'))
    },
    // 下载模板
    fetchTemplate() {
      var href1 = window.location.href
      var href2 = this.$route.path
      var url = href1.substring(0, href1.indexOf(href2))
      window.location.href = url + '/template/spvBaseInformationDataInitializationTemplate.xlsx'
    },
    // 文件上传变更时间
    handleFileChange(file, fileList) {
      if (!(file.name.indexOf('xls') >= 0 && file.name.indexOf('xlsx') >= 0)) {
        this.msgError(this.$t('仅允许导入“xls”或“xlsx”格式文件！'))
        fileList.splice(0, 1)
      }
    },
    // 导出项目
    exportDeal() {
      this.downLoadExcelPost('/view/searchMainView/export', { viewId: this.viewId }).then(() => {
        this.msgSuccess(this.$t('导出成功'))
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.list-row{
  .el-select{
    margin-bottom: 5px;
    width: 75%;
  }
}

.newMess .el-form,
.newMess .el-table {
  margin-bottom: 20px;
}

li {
  list-style: none;
}
.list-views {
  -webkit-box-align: center;
  -ms-flex-align: center;
  align-items: center;
  height: 52px;
  display: flex;
  margin: 0;
  padding: 0;
  overflow-x:auto ;
}
.tag-number {
  font-family: PingFangSC-Medium;
  font-size: 20px;
  color: #fff;
  line-height: 20px;
}
.tag-label {
  font-family: PingFangSC-Regular;
  font-size: 12px;
  color: #fff;
  line-height: 16px;
}

.list-views li.selected:after {
  position: absolute;
  content: "";
  display: block;
  top: 1px;
  right: 4px;
  width: 4px;
  height: 7px;
  border-style: solid;
  border-color: white;
  border-width: 0 2px 2px 0;
  transform: rotateZ(45deg);
}
.list-views li {
  margin-right: 10px;
  font-size: 12px;
  border-radius: 2px;
  width: 120px;
  min-width: 100px;
  height: 50px;
  -webkit-box-orient: vertical;
  -webkit-box-direction: normal;
  -ms-flex-direction: column;
  flex-direction: column;
  -webkit-box-pack: center;
  -ms-flex-pack: center;
  justify-content: center;
  -webkit-box-align: center;
  -ms-flex-align: center;
  align-items: center;
  cursor: pointer;
  background: #a4afeb;
  text-align: center;
  display: flex;
  position: relative;
}
.tag-views-title {
  display: inline-block;
  float: left;
  font-size: 14px;
}
.table-grid-content {
  border-radius: 4px;
  padding: 10px;
  margin-bottom: 15px;
}

.table-input {
  outline-style: none;
  border: 1px solid #ccc;
  border-radius: 3px;
  width: 200px;
  font-size: 14px;
  height: 30px;
}

.el-table td {
  padding: 4px 0;
  font-size: 13px;
}

.list-table {
  padding: 10px;
  -webkit-box-shadow: 0 3px 12px 2px rgba(218, 223, 232, 0.5);
  box-shadow: 0 3px 12px 2px rgba(218, 223, 232, 0.5);
  border: 1px solid #ebeef5;
  background-color: #fff;
  color: #303133;
  -webkit-transition: 0.3s;
  transition: 0.3s;
  border-radius: 4px;
  overflow: hidden;
}

.el-table__header th {
  background-color: #f6f7fb !important;
  padding: 2px 0;
}

.el-table .cell {
  white-space: nowrap;
}

.el-dialog {
  width: 800px;
}

.list-left {
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  padding-left: 10px;
}

.module-list-switch {
  display: flex;
  -webkit-box-align: center;
  -ms-flex-align: center;
  align-items: center;
}

.module-list-switch .list-switch {
  background: #f6f7fb;
  border-right: 1px solid #e6e9f5;
  width: 18px;
  height: 126px;
  font-size: 12px;
  color: #9da2b3;
  text-align: center;
  border-top-right-radius: 30px;
  border-bottom-right-radius: 30px;
  cursor: pointer;
  line-height: 16px;
}

.module-list-switch .list-switch i {
  -webkit-box-align: center;
  -ms-flex-align: center;
  align-items: center;
  vertical-align: initial;
  height: 100%;
  display: flex;
  font-style: normal;
}

.shai-side-collapsed {
  width: 220px;
  border-right: 1px solid #e6e9f5;
}

.shai-side-expanded {
  width: 0px;
  display: none;
}

.slideInRight,
.Table-table {
  display: flex;
}

.slideInRight {
  margin-right: 10px;
  height: 500px;
  margin-left: -10px;
}

.list-left .left-header {
  height: 40px !important;
  padding: 0;
  font-size: 14px;
  padding-right: 10px;
}

.list-left .left-main {
  margin-top: 10px;
  height: calc(100% - 85px);
  margin-bottom: 5px;
  overflow: auto;
  padding: 0;
}

.list-left .left-main .el-checkbox {
  display: block;
  margin-bottom: 5px;
}
.list-row {
  margin-bottom: 10px;
  width: 165px;
}

.list-left .left-footer {
  height: 33px !important;
  padding: 0;
  text-align: right;
  margin-right: 15px;
}
.field .el-transfer-panel {
  width: 260px !important;
}
.el-pagination {
  text-align: right;
  margin-top: 10px;
}
.tableDiv {
  position: relative;
  overflow: hidden;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
  -webkit-box-flex: 1;
  -ms-flex: 1;
  flex: 1;
  width: 100%;
  max-width: 100%;
  font-size: 14px;
  color: #606266;
}
.btnDiy {
  text-align: right;
}
.btnDiy button {
  padding: 8px 20px;
  border-radius: 0px;
}
.btnDiy .el-button + .el-button {
  margin-left: 0px;
}

.viewItem {
  margin: 15px 0 10px;
}
</style>
